package esercitazione3.tda_NodeList;

import java.util.Iterator;
import java.util.NoSuchElementException;

import esercitazione3.exceptions.BoundaryViolationException;
import esercitazione3.exceptions.InvalidPositionException;

public class ElementIterator<E> implements Iterator<E> {
	
	// Lista da scandire
	protected PositionList<E> list;
	// Cursore
	protected Position<E> cur = null;
	
	public ElementIterator(){
		
	}
	
	public ElementIterator(PositionList<E> l){
		list = l;
		
		try {
			if(!list.isEmpty()){
				cur = list.first();
			}
		} catch (EmptyListException e) {
			e.printStackTrace();
		}
	}
	
	public boolean hasNext() {
		return (cur!=null);
	}

	public E next() throws NoSuchElementException{
		
		E toReturn = null;

		if(!hasNext())
			throw new NoSuchElementException("Nessun altra posizione.");

		try {
			toReturn = cur.element();

			if(cur==list.last()){
				cur = null;
			}else{
				cur = list.next(cur);
			}

		} catch (InvalidPositionException e) {
			e.printStackTrace();
		} catch (EmptyListException e) {
			e.printStackTrace();
		} catch (BoundaryViolationException e){
			e.printStackTrace();
		}

		return toReturn;
	}

	public void remove() throws UnsupportedOperationException{
		throw new UnsupportedOperationException("remove");
	}

}
